package io.github.novaframe.common.util.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HttpUtil 使用HttpURLConnection原生实现
 * 
 * @author Locki
 * @date Apr 11, 2017 3:23:14 PM
 * @version 1.0
 *
 */
public class HttpUtil {

	private static final Logger LOG = LoggerFactory.getLogger(HttpUtil.class);
	private static final String DEFAULT_CHARSET = "UTF-8";

	/**
	 * HTTP POST 
	 * Content-Type: application/x-www-form-urlencoded
	 * 
	 * @param url
	 * @param data
	 * @return
	 * @throws IOException 
	 */
	public static String httpPost(String urlStr, Map<String, String> params) {
		
		URL url;
		HttpURLConnection urlConn = null;
		DataOutputStream out = null;
		String result = "";
		try {
			String paramsStr = "";
			int i = 0;
			for (Entry<String, String> entry : params.entrySet()) {
				String frag = "";
				if (i == 0) {
					frag = entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), DEFAULT_CHARSET);
				} else {
					frag = "&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), DEFAULT_CHARSET);
				}
				paramsStr += frag;
				i++;
			}
			
			url = new URL(urlStr);
			urlConn = (HttpURLConnection) url.openConnection();
			urlConn.setRequestMethod("POST");
			urlConn.setDoInput(true); // 向连接中写入数据
			urlConn.setDoOutput(true); // 从连接中读取数据
			urlConn.setUseCaches(false); // 禁止缓存
			urlConn.setInstanceFollowRedirects(true); // 自动执行HTTP重定向
			urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置内容类型
			
			out = new DataOutputStream(urlConn.getOutputStream()); // 获取输出流
			out.writeBytes(paramsStr);
			out.flush();
			
			
			if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStreamReader in = new InputStreamReader(urlConn.getInputStream()); // 获得读取的内容
                BufferedReader buffer = new BufferedReader(in); // 获取输入流对象
                String inputLine = null;
                while ((inputLine = buffer.readLine()) != null) {
                    result += inputLine + "\n";
                }
                in.close(); //关闭字符输入流
			}
			
			LOG.info("Http post result: " + result);
		} catch (UnsupportedEncodingException e) {
			LOG.error("Http url encode error: ", e);
		} catch (IOException e) {
			LOG.error("Http post error: ", e);
		} finally {
			if (urlConn != null) {
				urlConn.disconnect();
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {}
			}
		}
		
		return result;
	}

	/**
	 * HTTP POST 
	 * Content-Type: multipart/form-data
	 * 
	 * @param url
	 * @param files
	 * @param params
	 * @return
	 */
	public static String httpPostFile(String url, List<File> files, Map<String, String> params) {

		return null;
	}
}
